package com.edais.actions;

import cn.paypalm.sdk.mer.api.PayPalmAPISDK;
import cn.paypalm.sdk.mer.common.PaypalmException;
import cn.paypalm.sdk.mer.common.XMLDocument;
import com.edais.service.SMSService;
import com.edais.service.ThirdProductRouteService;
import com.edais.service.UserCardService;
import com.edais.service.UserMessageService;
import com.edais.util.CommonUtil;
import com.edais.util.MD5;
import com.edais.util.ThirdPartyEnvUtil;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一回调处理类
 */
@Controller
@RequestMapping("/thirdNotify")
public class ThirdNotifyAction implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private static final Log logger = LogFactory.getLog(ThirdNotifyAction.class);
	
	@Autowired
	private ThirdProductRouteService thirdProductRouteService;

    @Autowired
    private UserCardService userCardService;

	@Autowired
	private SMSService sMSService;

	@Autowired
	private UserMessageService userMessageService;

	/**
	 * 富友提现回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/fuyouWithdrawNotify")
	public void fuyouWithdrawNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ret_code = "0";//字符串“1” 代表通知成功，其他代表失败
		String logInfo = "fuyouWithdrawNotify富友提现回调，";

        String mchntCd = ThirdPartyEnvUtil.getValue("fuyou.mchntCd");; //商户号
		String mchntkey = ThirdPartyEnvUtil.getValue("fuyou.mchntkey"); //密钥

		String orderno = request.getParameter("orderno"); //商户请求流水
		logInfo = logInfo + "orderno="+orderno;
		logger.info(logInfo);
		String merdt = request.getParameter("merdt"); //请求日期
        String fuorderno = request.getParameter("fuorderno"); //富友流水
        String accntno = request.getParameter("accntno"); //账号
        String amt = request.getParameter("amt"); //退票金额
        String mac = request.getParameter("mac"); ////校验值--商户号|富友分配给商户的密钥|商户请求流水|原请求日期|账号|退票金额
        String state = request.getParameter("state"); //0交易未发送1交易已发送且成功2交易已发送且失败3交易发送中7	交易已发送且超时
        try {
            //商户号|富友分配给商户的密钥|商户请求流水|原请求日期|账号|退票金额
            String signPlain = mchntCd + "|" + mchntkey + "|" + orderno + "|" + merdt + "|" + accntno + "|"
                    + amt ;
            String sign = MD5.md5(signPlain);

            String ip = CommonUtil.getClientIP(request);
			String context = ",验签参数，signPlain="+signPlain+",MD5后的校验值为sign="+sign+",mac="+mac+",ip="+ip+",交易状态state="+state;
			logger.info(logInfo+context);

            logger.debug(logInfo+"异步通知校验值mac:" + mac+",拼接加密后的值sign:" + sign);
            if (mac.equals(sign)) {
				logger.info(logInfo+"富友提现异步通知验签成功!");
                /**
                 * 封装接口参数
                 */
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("oidPaybill", fuorderno);
                map.put("noOrder", orderno);
                logger.debug(logInfo+"noOrder:" + orderno);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String merOrderDate = sdf.format(new Date());
                logger.debug(logInfo+"moneyOrder:" + amt);
                map.put("moneyOrder", amt);
                map.put("dtOrder", merOrderDate);

                String resultPay = "FAILD";
                if ("1".equals(state)) {
                    resultPay = "SUCCESS";
                }
                map.put("resultPay", resultPay);

                Map<String, Object> jsonMap = new HashMap<String, Object>();
                jsonMap = this.userCardService.llpayWithdrawalsNotify(map);
                String rescode = String.valueOf(jsonMap.get("rescode"));
                if ("00000".equals(rescode)) {
                    ret_code = "1";
                } else if ("99998".equals(rescode)) {
                    ret_code = "99998";
                } else if ("99997".equals(rescode)) {
                    // 代表连连支付订单已经处理成功 不再发送短信相关
                    ret_code = "1";
                }
            }else{
                logger.info(logInfo+"富友提现异步通知验签失败!");
            }
        } catch (Exception e) {
            logger.info(logInfo+"富友提现异步通知异常!" + e.getMessage());
        }
        response.getWriter().write(ret_code);
        response.getWriter().close();

	}
	
	/**
	 * 富有充值回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/fuyouSinglePayNofity")
	public void fuyouSinglePayNofity(HttpServletRequest request, HttpServletResponse response){
		
		String reqOrderId = request.getParameter("MCHNTORDERID");
		String resOrderId = request.getParameter("ORDERID");
		String tradeAmount = request.getParameter("AMT");
		String fuyouResCode = request.getParameter("RESPONSECODE");
		String fuyouResMsg = request.getParameter("RESPONSEMSG");
		String version = request.getParameter("VERSION");
		String bankCard = request.getParameter("BANKCARD");
		String mchntCd = request.getParameter("MCHNTCD");
		String type = request.getParameter("TYPE");
		
		String sign = request.getParameter("SIGN");
		
		String payFlag = "WX";
		String receiveMessage = JSONObject.fromObject(request.getParameterMap()).toString();
		String logInfo = "富有支付回调"+reqOrderId;
		Map<String,Object> requestMap = new HashMap<String,Object>();
		requestMap.put("reqOrderId", reqOrderId);
		requestMap.put("payFlag", payFlag);
		BigDecimal realAmt = new BigDecimal(tradeAmount).divide(new BigDecimal(100));
		requestMap.put("tradeAmount", realAmt.toString());
		requestMap.put("resOrderId", resOrderId);
		requestMap.put("receiveMessage", receiveMessage);
		
		try{
			
			
			logger.info("================================="+logInfo+"开始回调");
			
			String mchntKey = ThirdPartyEnvUtil.getValue("fuyou.api.mchnt.key");
			
			String signPain = new StringBuffer().append(type).append("|").append(version).append("|").append(fuyouResCode)
					.append("|").append(mchntCd).append("|").append(reqOrderId).append("|").append(resOrderId).append("|")
					.append(tradeAmount).append("|").append(bankCard).append("|").append(mchntKey).toString();
			logger.info(logInfo+"接收结果签名明文："+signPain.toString());
			
			if (!MD5.md5(signPain).equals(sign)){
				logger.info(logInfo+"商户号验证签名失败.");
				return;
			}
			if(fuyouResCode.equals("0000")){
				ResultDTO<Map<String,Object>> resultDTO = this.thirdProductRouteService.singlePayNotifyNew(requestMap);
				logger.info(logInfo+"回调结束返回码"+resultDTO.getResCode());
				
				if(resultDTO.getResCode().equals(ResultCode.SUCCESS)){
					response.setStatus(HttpStatus.SC_OK);
				}else{
					response.setStatus(HttpStatus.SC_MOVED_TEMPORARILY);
				}
				return;
			}else{
				logger.info(logInfo+"充值失败，编码"+fuyouResCode+"返回信息"+fuyouResMsg);
			}
			
		}catch (Exception e) {
			response.setStatus(HttpStatus.SC_MOVED_TEMPORARILY);
			return;
		}
		
	}

	/**
	 * 掌上汇通充值回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/zshtSinglePayNofity")
	public void zshtSinglePayNofity(HttpServletRequest request, HttpServletResponse response){
		String transData = request.getParameter("transdata");
		String logInfo = "掌上汇通支付回调";
		XMLDocument resXML;
		String merRepData = "";
		
		try{
			merRepData = PayPalmAPISDK.encryptData("faild", PayPalmAPISDK.XML);
			resXML = PayPalmAPISDK.getReturnData(transData);
			logger.info("解密后数据：" + resXML);
			// 商户订单号
			String merOrderNo = resXML.getValueAt("merorderno").toString();
			
			logInfo = logInfo+merOrderNo;
			
			// 订单状态 0等待支付 1支付成功 2支付失败
			String orderStatus = resXML.getValueAt("orderstatus").toString();
			// 错误码
			String rspCode = resXML.getValueAt("rspcode").toString();
			// 错误描述
			String rspDesc = resXML.getValueAt("rspdesc").toString();
			String payFlag = "WX";
			
			JSONObject jsonObject = JSONObject.fromObject(resXML.getMapFromXml());
			String receiveMessage = jsonObject.toString();
			if ("1".equals(orderStatus)) {
				String tranamt = resXML.getValueAt("tranamt").toString();
				String resOrderId = resXML.getValueAt("orderno").toString();
				
				Map<String,Object> requestMap = new HashMap<String,Object>();
				requestMap.put("reqOrderId", merOrderNo);
				requestMap.put("payFlag", payFlag);
				BigDecimal realAmt = new BigDecimal(tranamt).divide(new BigDecimal(100));
				requestMap.put("tradeAmount", realAmt.toString());
				requestMap.put("resOrderId", resOrderId);
				requestMap.put("receiveMessage", receiveMessage);
				
				logger.info(logInfo+"开始回调");
				ResultDTO<Map<String,Object>> resultDTO = this.thirdProductRouteService.singlePayNotifyNew(requestMap);
				logger.info(logInfo+"回调结束返回码"+resultDTO.getResCode());
				
				if(resultDTO.getResCode().equals(ResultCode.SUCCESS)){
					merRepData = PayPalmAPISDK.encryptData("success", PayPalmAPISDK.XML);
				}
				return;
			}else{
				logger.info(logInfo+"充值失败，编码"+rspCode+"返回信息"+rspDesc);
			}
			response.getWriter().write(merRepData);
			response.getWriter().close();
			
		} catch (PaypalmException e) {
			logger.info(logInfo +"报错",e);
		} catch (UnsupportedEncodingException e) {
			logger.info(logInfo +"报错",e);
		} catch (IOException e) {
			logger.info(logInfo +"报错",e);
		} catch (Exception e) {
			logger.info(logInfo +"报错",e);
		}
	}

}
